package net.thxjj.mobileServer.util;

import net.thxjj.mobileServer.entity.Const;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class JWTUtils {

    /**
     * HMACSHA256
     * @param enheader,enpayload
     * @return string
     */
    public static String GetSecret(String enheader, String enpayload) throws Exception {

        return HMACSHA256(enheader+"."+enpayload,Const.SECRET);
    }

    public static String ProduceToken(String payload) throws Exception{
        String enheader = Base64Util.base64Encode(Const.ACCESS_TOKEN_HEADER);
        String enpayload = Base64Util.base64Encode(payload);
       return enheader+"."+enpayload+"."+GetSecret(enheader,enpayload);
    }

    public static String HMACSHA256(String data, String key) throws Exception {

        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");

        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");

        sha256_HMAC.init(secret_key);

        byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));

        StringBuilder sb = new StringBuilder();

        for (byte item : array) {

            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));

        }

        return sb.toString().toUpperCase();

    }

    public static void main(String args[]) {
        String ads = null;
        try {
            ads = ProduceToken("{ \"sub\": \"1234567890\", \"name\": \"John Doe\", \"admin\": true }");
            System.out.println(ads);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
